﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace ComicsEditor
{
    public class FrameDrawInstrument : Instrument
    {
        public DashedRect DashedRect = null;

        public FrameDrawInstrument()
        {
        }

        public override void Bind(PageInfo PageInfo)
        {
            base.Bind(PageInfo);

            if (DashedRect != null)
                DashedRect.Dispose();
            DashedRect = new DashedRect(Page, Rectangle.Empty);
            DashedRect.Hide();
        }

        public override bool Activate(Point point, out Point offset)
        {
            offset = Point.Empty;
            DashedRect.Rectangle = new Rectangle(point, new Size(1, 1));
            DashedRect.Show();
            return true;
        }

        public override void Drag(Point newPoint, Point offset, Point deltaActivate, Point deltaMove)
        {
            if (deltaActivate.X >= 0)
            {
                DashedRect.Rectangle.X = newPoint.X - deltaActivate.X;
                DashedRect.Rectangle.Width = deltaActivate.X + 1;
            }
            else
            {
                DashedRect.Rectangle.X = newPoint.X;
                DashedRect.Rectangle.Width = 1 - deltaActivate.X;
            }
            if (deltaActivate.Y >= 0)
            {
                DashedRect.Rectangle.Y = newPoint.Y - deltaActivate.Y;
                DashedRect.Rectangle.Height = deltaActivate.Y + 1;
            }
            else
            {
                DashedRect.Rectangle.Y = newPoint.Y;
                DashedRect.Rectangle.Height = 1 - deltaActivate.Y;
            }
            if (DashedRect.Rectangle.X < 0)
            {
                DashedRect.Rectangle.Width += DashedRect.Rectangle.X;
                DashedRect.Rectangle.X = 0;
            }
            if (DashedRect.Rectangle.Y < 0)
            {
                DashedRect.Rectangle.Height += DashedRect.Rectangle.Y;
                DashedRect.Rectangle.Y = 0;
            }
            if (DashedRect.Rectangle.Right > Page.Width)
                DashedRect.Rectangle.Width = Page.Width - DashedRect.Rectangle.X;
            if (DashedRect.Rectangle.Bottom > Page.Height)
                DashedRect.Rectangle.Height = Page.Height - DashedRect.Rectangle.Y;
            Page.Changed = true;
        }

        public override void Deactivate()
        {
            DashedRect.Hide();
            if (DashedRect.Rectangle.Width > 30 && DashedRect.Rectangle.Height > 30)
            {
                Frame frame = new Frame(Page, DashedRect.Rectangle, true);
                pageInfo.Frames.Add(frame);
                if (pageInfo.FrameCreate != null)
                    pageInfo.FrameCreate(frame);
            }
        }
    }
}
